package com.abocode.aichat.server.context.delivery.outbound;


import com.abocode.aichat.api.ReplayResultBuilder;
import com.abocode.aichat.data.Entity;
import com.abocode.aichat.data.MessageStanza;
import com.abocode.aichat.server.context.ServerRuntimeContext;
import com.abocode.aichat.server.context.delivery.AbstractServerDeliver;
import com.abocode.aichat.api.ReplayResult;
import com.abocode.aichat.server.context.delivery.reply.Replies;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * @author guanxf
 */
@Slf4j
public class OutboundServerDeliver extends AbstractServerDeliver<Replies> {
    class OutboundReplyCallable implements Callable<ReplayResult> {
        private ServerRuntimeContext serverRuntimeContext;

        public MessageStanza stanza;

        public OutboundReplyCallable(ServerRuntimeContext serverRuntimeContext, MessageStanza stanza) {
            this.stanza = stanza;
            this.serverRuntimeContext = serverRuntimeContext;
        }

        @Override
        public ReplayResult call() {
            try {
                //拿到链接
                Entity entity = stanza.findTo();
                if (entity != null) {
                    List<Channel> channles = getServerRuntimeContext().getProtocolChannelRegistry().get(entity);
                    if (channles != null && !channles.isEmpty()) {
                        for (Channel channel : channles) {
                            serverRuntimeContext.getWorker().execute(channel, stanza);
                        }
                    }
                }
            } catch (Exception ex) {
                log.error("call Exception", ex);
                return ReplayResultBuilder.failure();
            }
            return ReplayResultBuilder.success();
        }
    }

    @Override
    public void deliver(Replies replies, MessageStanza stanza) {
        executor.submit(new OutboundReplyCallable(getServerRuntimeContext(), stanza));
    }
}
